<template>
  <div class="appointment-detail-container">
    <el-page-header @back="router.back()" title="返回">
      <template #content>
        <span class="title">预约详情</span>
      </template>
    </el-page-header>

    <div class="content" v-loading="loading">
      <el-card v-if="appointment" class="detail-card">
        <!-- 状态标签 -->
        <div class="status-banner" :class="`status-${appointment.status}`">
          <el-icon :size="32">
            <Clock v-if="appointment.status === 0" />
            <Select v-else-if="appointment.status === 1" />
            <Close v-else-if="appointment.status === 2 || appointment.status === 4" />
            <VideoPlay v-else-if="appointment.status === 3" />
            <Check v-else-if="appointment.status === 5" />
          </el-icon>
          <h2>{{ getStatusText(appointment.status) }}</h2>
        </div>

        <!-- 预约信息 -->
        <div class="section">
          <h3 class="section-title">
            <el-icon><Document /></el-icon>
            预约信息
          </h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="预约编号">
              {{ appointment.id }}
            </el-descriptions-item>
            <el-descriptions-item label="预约状态">
              <el-tag :type="getStatusType(appointment.status)">
                {{ getStatusText(appointment.status) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="技能名称" :span="2">
              <el-link type="primary" @click="viewSkill(appointment.skillId)">
                {{ appointment.skillTitle }}
              </el-link>
            </el-descriptions-item>
            <el-descriptions-item label="预约时间" :span="2">
              {{ formatTime(appointment.appointmentTime) }}
            </el-descriptions-item>
            <el-descriptions-item label="时长">
              {{ appointment.duration }} 分钟
            </el-descriptions-item>
            <el-descriptions-item label="时间币">
              {{ appointment.timeCoins }}
            </el-descriptions-item>
            <el-descriptions-item label="创建时间" :span="2">
              {{ formatTime(appointment.createTime) }}
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 参与人信息 -->
        <div class="section">
          <h3 class="section-title">
            <el-icon><User /></el-icon>
            参与人信息
          </h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-card shadow="hover" class="user-card">
                <div class="user-info-detail">
                  <el-avatar :size="60" :src="appointment.requesterAvatar">
                    {{ appointment.requesterNickname?.[0] }}
                  </el-avatar>
                  <div class="user-details">
                    <h4>预约发起人</h4>
                    <p class="nickname">{{ appointment.requesterNickname }}</p>
                    <p class="meta">{{ appointment.requesterSchool }} · {{ appointment.requesterMajor }}</p>
                    <el-button
                      size="small"
                      @click="startChat(appointment.requesterId)"
                      style="margin-top: 8px"
                    >
                      <el-icon><ChatDotRound /></el-icon>
                      发消息
                    </el-button>
                  </div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="12">
              <el-card shadow="hover" class="user-card">
                <div class="user-info-detail">
                  <el-avatar :size="60" :src="appointment.providerAvatar">
                    {{ appointment.providerNickname?.[0] }}
                  </el-avatar>
                  <div class="user-details">
                    <h4>技能提供者</h4>
                    <p class="nickname">{{ appointment.providerNickname }}</p>
                    <p class="meta">{{ appointment.providerSchool }} · {{ appointment.providerMajor }}</p>
                    <el-button
                      size="small"
                      @click="startChat(appointment.providerId)"
                      style="margin-top: 8px"
                    >
                      <el-icon><ChatDotRound /></el-icon>
                      发消息
                    </el-button>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>

        <!-- 留言信息 -->
        <div class="section" v-if="appointment.message">
          <h3 class="section-title">
            <el-icon><ChatLineRound /></el-icon>
            预约留言
          </h3>
          <el-card shadow="never" class="message-card">
            <p>{{ appointment.message }}</p>
          </el-card>
        </div>

        <!-- 操作按钮 -->
        <div class="actions">
          <!-- 待确认状态 - 提供者可确认/拒绝 -->
          <template v-if="appointment.status === 0 && isProvider">
            <el-button type="success" @click="handleConfirm" :loading="confirming">
              <el-icon><Select /></el-icon>
              确认预约
            </el-button>
            <el-button type="danger" @click="handleReject" :loading="rejecting">
              <el-icon><Close /></el-icon>
              拒绝预约
            </el-button>
          </template>

          <!-- 待确认状态 - 请求者可取消 -->
          <template v-if="appointment.status === 0 && isRequester">
            <el-button type="warning" @click="handleCancel" :loading="canceling">
              <el-icon><Close /></el-icon>
              取消预约
            </el-button>
          </template>

          <!-- 已确认状态 - 双方可开始 -->
          <template v-if="appointment.status === 1">
            <el-button type="primary" @click="handleStart" :loading="starting">
              <el-icon><VideoPlay /></el-icon>
              开始预约
            </el-button>
            <el-button type="warning" @click="handleCancel" :loading="canceling">
              <el-icon><Close /></el-icon>
              取消预约
            </el-button>
          </template>

          <!-- 进行中状态 - 双方可完成 -->
          <template v-if="appointment.status === 3">
            <el-button type="success" @click="handleComplete" :loading="completing">
              <el-icon><Check /></el-icon>
              完成预约
            </el-button>
          </template>

          <!-- 已完成状态 - 可评价 -->
          <template v-if="appointment.status === 5 && !appointment.hasReviewed">
            <el-button type="warning" @click="showReviewDialog">
              <el-icon><Star /></el-icon>
              评价对方
            </el-button>
          </template>
        </div>
      </el-card>
    </div>

    <!-- 评价对话框 -->
    <ReviewDialog
      v-model:visible="reviewDialogVisible"
      :appointment-id="appointment?.id"
      :reviewee-id="revieweeId"
      @success="handleReviewSuccess"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Clock,
  Select,
  Close,
  VideoPlay,
  Check,
  Document,
  User,
  ChatLineRound,
  ChatDotRound,
  Star
} from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { useUserStore } from '@/stores/user'
import {
  getAppointmentDetail,
  confirmAppointment,
  rejectAppointment,
  cancelAppointment,
  startAppointment,
  completeAppointment
} from '@/api/appointment'
import ReviewDialog from '@/components/ReviewDialog.vue'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

const loading = ref(false)
const appointment = ref(null)
const confirming = ref(false)
const rejecting = ref(false)
const canceling = ref(false)
const starting = ref(false)
const completing = ref(false)
const reviewDialogVisible = ref(false)

const isProvider = computed(() => {
  return appointment.value?.providerId === userStore.userInfo?.id
})

const isRequester = computed(() => {
  return appointment.value?.requesterId === userStore.userInfo?.id
})

const revieweeId = computed(() => {
  return isRequester.value ? appointment.value?.providerId : appointment.value?.requesterId
})

const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}

const getStatusText = (status) => {
  const statusMap = {
    0: '待确认',
    1: '已确认',
    2: '已拒绝',
    3: '进行中',
    4: '已取消',
    5: '已完成'
  }
  return statusMap[status] || '未知'
}

const getStatusType = (status) => {
  const typeMap = {
    0: 'warning',
    1: 'success',
    2: 'danger',
    3: 'primary',
    4: 'info',
    5: ''
  }
  return typeMap[status] || ''
}

const fetchAppointmentDetail = async () => {
  const id = route.params.id
  if (!id) {
    ElMessage.error('预约ID不存在')
    router.back()
    return
  }

  loading.value = true
  try {
    const res = await getAppointmentDetail(id)
    appointment.value = res.data
  } catch (error) {
    console.error('获取预约详情失败：', error)
    ElMessage.error('获取预约详情失败')
    router.back()
  } finally {
    loading.value = false
  }
}

const handleConfirm = async () => {
  try {
    await ElMessageBox.confirm('确定要确认此预约吗？', '提示', { type: 'success' })
    confirming.value = true
    await confirmAppointment(appointment.value.id)
    ElMessage.success('确认成功')
    fetchAppointmentDetail()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认失败：', error)
    }
  } finally {
    confirming.value = false
  }
}

const handleReject = async () => {
  try {
    await ElMessageBox.confirm('确定要拒绝此预约吗？', '提示', { type: 'warning' })
    rejecting.value = true
    await rejectAppointment(appointment.value.id)
    ElMessage.success('已拒绝')
    fetchAppointmentDetail()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('拒绝失败：', error)
    }
  } finally {
    rejecting.value = false
  }
}

const handleCancel = async () => {
  try {
    await ElMessageBox.confirm('确定要取消此预约吗？', '提示', { type: 'warning' })
    canceling.value = true
    await cancelAppointment(appointment.value.id)
    ElMessage.success('已取消')
    fetchAppointmentDetail()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消失败：', error)
    }
  } finally {
    canceling.value = false
  }
}

const handleStart = async () => {
  try {
    await ElMessageBox.confirm('确定要开始此预约吗？', '提示', { type: 'primary' })
    starting.value = true
    await startAppointment(appointment.value.id)
    ElMessage.success('已开始')
    fetchAppointmentDetail()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('开始失败：', error)
    }
  } finally {
    starting.value = false
  }
}

const handleComplete = async () => {
  try {
    await ElMessageBox.confirm('确定要完成此预约吗？', '提示', { type: 'success' })
    completing.value = true
    await completeAppointment(appointment.value.id)
    ElMessage.success('已完成')
    fetchAppointmentDetail()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('完成失败：', error)
    }
  } finally {
    completing.value = false
  }
}

const viewSkill = (skillId) => {
  router.push(`/skill/detail/${skillId}`)
}

const startChat = (userId) => {
  router.push({
    path: '/chat',
    query: { userId }
  })
}

const showReviewDialog = () => {
  reviewDialogVisible.value = true
}

const handleReviewSuccess = () => {
  ElMessage.success('感谢您的评价')
  fetchAppointmentDetail()
}

onMounted(() => {
  fetchAppointmentDetail()
})
</script>

<style scoped>
.appointment-detail-container {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 20px;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.content {
  max-width: 1200px;
  margin: 20px auto;
}

.detail-card {
  background: white;
  border-radius: 8px;
}

.status-banner {
  text-align: center;
  padding: 30px;
  border-radius: 8px;
  margin-bottom: 30px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.status-banner h2 {
  margin: 0;
  font-size: 24px;
}

.status-0 {
  background: linear-gradient(135deg, #ffeaa7 0%, #fdcb6e 100%);
  color: #d63031;
}

.status-1 {
  background: linear-gradient(135deg, #a8e6cf 0%, #55efc4 100%);
  color: #00b894;
}

.status-2,
.status-4 {
  background: linear-gradient(135deg, #dfe6e9 0%, #b2bec3 100%);
  color: #636e72;
}

.status-3 {
  background: linear-gradient(135deg, #74b9ff 0%, #0984e3 100%);
  color: #fff;
}

.status-5 {
  background: linear-gradient(135deg, #81ecec 0%, #00cec9 100%);
  color: #00b894;
}

.section {
  margin-bottom: 30px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #303133;
}

.user-card {
  height: 100%;
}

.user-info-detail {
  display: flex;
  gap: 15px;
  align-items: flex-start;
}

.user-details {
  flex: 1;
}

.user-details h4 {
  margin: 0 0 8px 0;
  color: #909399;
  font-size: 14px;
  font-weight: normal;
}

.user-details .nickname {
  font-size: 18px;
  font-weight: bold;
  margin: 0 0 5px 0;
  color: #303133;
}

.user-details .meta {
  color: #909399;
  font-size: 14px;
  margin: 0;
}

.message-card {
  background: #f5f7fa;
}

.message-card p {
  margin: 0;
  line-height: 1.8;
  white-space: pre-wrap;
}

.actions {
  display: flex;
  justify-content: center;
  gap: 15px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.el-descriptions {
  margin-top: 10px;
}

:deep(.el-descriptions__label) {
  width: 120px;
}
</style>

